﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.View
{
    public partial class ThreadReplyPage : PhoneApplicationPage
    {
        private PostCollection posting;
        private Post selectedPost;
        private Thread currentForum;

        public ThreadReplyPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.THREAD))
            {
                currentForum = (Thread)PhoneApplicationService.Current.State[Config.THREAD];
                if (currentForum != null && currentForum.Id != null)
                {
                    textBlockJudul.Text = currentForum.Judul;
                    LoadPosting(currentForum);
                }
                else
                {
                    textBlockJudul.Text = "";
                    textBoxComment.Text = "";
                }
            }
        }

        private void buttonCancel_Click(object sender, System.EventArgs e)
        {
            NavigationService.GoBack();
        }

        private void buttonSave_Click(object sender, System.EventArgs e)
        {
            Post post = new Post
            {
                Comment = textBoxComment.Text,
                Sender = SavedUser.Instance.User,
                Forum = currentForum
            };
            AddPosting(post);
            textBoxComment.Text = string.Empty;
        }

        private void buttonSend_Click(object sender, RoutedEventArgs e)
        {
            Post post = new Post
            {
                Comment = textBoxComment.Text,
                Sender = SavedUser.Instance.User,
                Forum = currentForum
            };
            AddPosting(post);
            textBoxComment.Text = string.Empty;
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Hapus komentar anda?", "Delete Confirmation", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                DeleteCurrentPost(selectedPost);
            }
        }

        private void ListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                Post post = (Post)e.AddedItems[0];

                selectedPost = post;

                if (SavedUser.Instance.User.Id == post.Sender.Id)
                {
                    ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = true;
                }
                else
                {
                    ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = false;
                }
            }
        }

        private void LoadPosting(Thread forum)
        {
            string json = JsonConvert.SerializeObject(forum);
            string url = Config.Instance.POST_SERVICE_URL() + Config.VIEW_ACTION_KEY;

            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listPosting_UploadStringCompleted);
            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void listPosting_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                posting = new PostCollection();
                PostCollection list = JsonConvert.DeserializeObject<PostCollection>(e.Result);
                foreach (Post post in list)
                {
                    Post msg = post;
                    msg.Side = post.Sender != null ? (post.Sender.Id.Equals(SavedUser.Instance.User.Id) ? PostSide.Me : PostSide.You) : PostSide.You;
                    
                    User user = post.Sender;
                    user.Nama = user != null ? (user.Id.Equals(SavedUser.Instance.User.Id) ? "Pengirim : Saya" : "Pengirim : " + user.Nama) : "Pengirim : Anonymous";
                    msg.Sender = user;
                    
                    posting.Add(msg);
                }
                listPosting.ItemsSource = posting;
                if(listPosting.Items.Count > 0)
                    listPosting.ScrollIntoView(listPosting.Items[listPosting.Items.Count - 1]);
                listPosting.UpdateLayout();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = false;
        }

        private void textBoxComment_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(textBoxComment.Text))
            {
                buttonSend.IsEnabled = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
            }
            else
            {
                buttonSend.IsEnabled = true;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
            }
        }

        private void AddPosting(Post posting)
        {
            string json = JsonConvert.SerializeObject(posting);
            string url = Config.Instance.POST_SERVICE_URL() + Config.ADD_ACTION_KEY;

            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(addPosting_UploadStringCompleted);
            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void addPosting_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                MessageBox.Show(e.Result);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            LoadPosting(currentForum);
        }

        private void DeleteCurrentPost(Post posting)
        {
            string json = JsonConvert.SerializeObject(posting);
            string url = Config.Instance.POST_SERVICE_URL() + Config.DELETE_ACTION_KEY;

            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(deletePosting_UploadStringCompleted);
            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void deletePosting_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }

                if (e.Result.Contains("Success"))
                {
                    MessageBox.Show("Komentar anda sudah di hapus.");
                    LoadPosting(currentForum);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
            LoadPosting(currentForum);
        }
    
    }
}